package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.PaymentFaildeException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCardMapper;
import com.sky.mapper.UserAddressBookMappper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.server.WebSocketServer;
import com.sky.service.UserOrderService;
import com.sky.vo.HistoryOrderVO;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class UserOrderServiceImpl implements UserOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserAddressBookMappper userAddressBookMappper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCardMapper shoppingCardMapper;
    @Autowired
    private UsershoppingCardServiceImpl usershoppingCardService;
    @Autowired
    private WebSocketServer webSocketServer;


    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());


        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<HistoryOrderVO> page = orderMapper.historyOrders(ordersPageQueryDTO);

        long total = page.getTotal();
        List<HistoryOrderVO> result = page.getResult();

        log.info(Arrays.toString(result.toArray()));

        for (HistoryOrderVO Order : result) {
            Long orderId = Order.getId();
            List<OrderDetail> orderDetail = orderMapper.historyOrdersDetail(orderId);
            Order.setOrderDetailList(orderDetail);
        }

        return new PageResult(total,result);
    }

    @Override
    public HistoryOrderVO orderDetail(Long id) {
        HistoryOrderVO order = orderMapper.order(id);

        List<OrderDetail> orderDetails = orderMapper.orderDetail(id);
        order.setOrderDetailList(orderDetails);
        return order;
    }

    /*
    * 提交订单
    * */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) throws IOException {
        //完善订单信息
        Orders orders = new Orders();
        log.info("前端传进来的提交的订单信息：{}", ordersSubmitDTO);
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = userAddressBookMappper.getById(addressBookId);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        User user = userMapper.getByUserId(BaseContext.getCurrentId());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());

        orderMapper.insert(orders);

        //插入订单详情
        List<OrderDetail> orderDetails = new ArrayList<>();
        List<ShoppingCart> shoppingCarts = shoppingCardMapper.getList(BaseContext.getCurrentId());
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderMapper.insertBatch(orderDetails);

        //清空购物车
        usershoppingCardService.clean();


        //todo 模拟用户提交订单后商家会语言播报
        //由于没有开通支付功能所以，模拟提交订单就算支付成功
        Map jsonmap = new HashMap();
        jsonmap.put("type",1); //表示来单提醒
        jsonmap.put("orderId",orders.getId());
        jsonmap.put("content","订单号："+ orders.getNumber());

        String jsonString = JSON.toJSONString(jsonmap);

        webSocketServer.sendToAllClient(jsonString);



        //返回
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderAmount(BigDecimal.valueOf(orders.getAmount() .intValue()+orders.getPackAmount()));
        orderSubmitVO.setOrderTime(LocalDateTime.now());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setId(orders.getId());
        System.out.println("submit的返回值："+orderSubmitVO);

        return orderSubmitVO;
    }

    @Override
    public void cancel(Long id) {

        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(id);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.cancel(orders);


    }

    @Transactional
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersPaymentDTO, orders);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setNumber(ordersPaymentDTO.getOrderNumber());
        orders.setCheckoutTime(LocalDateTime.now());


        int total = orderMapper.payment(orders);

        if (total>=1) {
            OrderPaymentVO orderPaymentVO = new OrderPaymentVO();
            orderPaymentVO.setNonceStr("hsincniahoia");
            orderPaymentVO.setPaySign("cnejncs");
            orderPaymentVO.setTimeStamp("caiojcwio");
            orderPaymentVO.setSignType("cesjiojc");
            orderPaymentVO.setPackageStr("mcopneio");
            return orderPaymentVO;
        }
        //todo 支付功能未开通

        /*else{
            throw new
        }*/
        return null;
    }


}
